package ch.bfh.ti.pixelator.camera;

import java.io.IOException;

import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Preview extends SurfaceView implements SurfaceHolder.Callback {
	private Camera camera;
	private ReceivePreviewCallback previewCallback;
	private boolean useCameraLock;

	private void init(Context context) {
		// Don't go to sleep
		setKeepScreenOn(true);

		// Get the settings
		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(context);
		useCameraLock = pref.getBoolean("prefUseCameraLock", false);
				
		/*
		 * Add the autofocus functionality. Autofocus is triggered when the user
		 * touches the screen.
		 */
		setOnClickListener(new LinearLayout.OnClickListener() {

			@Override
			public void onClick(View view) {
				camera.autoFocus(null);

				// auto exposure and white balance lock
				if (useCameraLock) {
					final Parameters params = camera.getParameters();
					if (params.isAutoExposureLockSupported()
							&& params.isAutoExposureLockSupported()) {
						if (params.getAutoExposureLock()) {
							params.setAutoExposureLock(false);
							params.setAutoWhiteBalanceLock(false);
							camera.setParameters(params);
							try {
								Thread.sleep(2000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						params.setAutoExposureLock(true);
						params.setAutoWhiteBalanceLock(true);
						camera.setParameters(params);
					}
				}
			}
		});

		getHolder().addCallback(this);
	}

	public Preview(Context context) {
		super(context);
		init(context);
	}

	public Preview(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public Preview(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	@Override
	protected void onMeasure(int width, int height) {
		final int w = resolveSize(getSuggestedMinimumWidth(), width);
		final int h = (int) ((float) w / 3.0 * 4.0);

		setMeasuredDimension(w, h);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// open main camera
		CameraManager manager = new CameraManager(getContext());
		camera = manager.OpenSelectedCameraWithDefaultParameters();

		try {
			camera.setPreviewDisplay(holder);
		} catch (IOException e) {
			Toast.makeText(getContext(), "Could not set preview",
					Toast.LENGTH_LONG).show();
		}

		camera.startPreview();

		previewCallback = new ReceivePreviewCallback(getContext());
		camera.setPreviewCallbackWithBuffer(previewCallback);

		requestLayout();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if (camera != null) {
			camera.stopPreview();
			camera.setPreviewCallback(null);
			camera.release();
			holder.removeCallback(this);
			camera = null;
		}
		previewCallback.shutdown();
		previewCallback = null;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		requestLayout();
	}
}